package com.fable.sp.core.util;

import com.google.common.base.Charsets;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

public final class UrlUtils {

    private UrlUtils() {
    }

    public static String build(String path, Map<String, ?> args) {
        if (args == null) return path;

        StringBuilder sb = new StringBuilder(64);
        sb.append(path);
        boolean isFirst = true;
        for (Map.Entry<String, ?> entry : args.entrySet()) {
            if (isFirst) {
                isFirst = false;
                int i = path.indexOf('?');
                switch (i) {
                    case -1:
                        sb.append('?');
                        break;
                    case 0:
                        break;
                    default:
                        sb.append('&');
                }
            } else {
                sb.append('&');
            }
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value == null) {
                sb.append(key);
            } else if (value instanceof Iterable) {
                boolean isFirst1 = true;
                for (Object value1 : (Iterable) value) {
                    if (value1 == null) continue;
                    if (isFirst1) {
                        isFirst1 = false;
                    } else {
                        sb.append('&');
                    }
                    sb.append(key).append('=').append(encodeURL(value1.toString()));
                }
            } else if (value.getClass().isArray()) {
                boolean isFirst1 = true;
                for (Object value1 : (Object[]) value) {
                    if (value1 == null) continue;
                    if (isFirst1) {
                        isFirst1 = false;
                    } else {
                        sb.append('&');
                    }
                    sb.append(key).append('=').append(encodeURL(value1.toString()));
                }
            } else {
                sb.append(key).append('=').append(encodeURL(value.toString()));
            }
        }
        return sb.toString();
    }

    public static String encodeURL(String text) {
        if (text == null) {
            return StringUtils.EMPTY;
        }
        try {
            return URLEncoder.encode(text, Charsets.UTF_8.displayName());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String decodeURL(String text) {
        if (text == null) {
            return StringUtils.EMPTY;
        }
        try {
            return URLDecoder.decode(text, Charsets.UTF_8.displayName());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
